package com.foreverwin.mes.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.OracleTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Ervin Chen
 * @date 2019/12/30 14:04
 */
public class MpGenerator {
    private AutoGenerator autoGenerator;

    private MpGenerator( AutoGenerator autoGenerator ){
        this.autoGenerator = autoGenerator;
    }

    public static MpGeneratorBuilder builder(){
        return new MpGeneratorBuilder();
    }

    public void execute(){
        this.autoGenerator.execute();
    }

    static class MpGeneratorBuilder{
        private GlobalConfig globalConfig = null;
        private DataSourceConfig dataSourceConfig = null;
        private StrategyConfig strategyConfig = null;
        private PackageConfig packageConfig = null;
        private InjectionConfig injectionConfig = null;
        private TemplateConfig templateConfig = null;
        private String basePath = null;
        private String[] tablePrefix = null;
        private String packageName = null;
        private String versionFieldName = null;
        private String author = null;
        private String[] tables = null;

        public MpGeneratorBuilder globalConfig( GlobalConfig globalConfig ){
            this.globalConfig = globalConfig;
            return this;
        }

        public MpGeneratorBuilder dataSourceConfig( DataSourceConfig dataSourceConfig ){
            this.dataSourceConfig = dataSourceConfig;
            return this;
        }

        public MpGeneratorBuilder strategyConfig( StrategyConfig strategyConfig ){
            this.strategyConfig = strategyConfig;
            return this;
        }

        public MpGeneratorBuilder packageConfig( PackageConfig packageConfig ){
            this.strategyConfig = strategyConfig;
            return this;
        }

        public MpGeneratorBuilder injectionConfig( InjectionConfig injectionConfig ){
            this.injectionConfig = injectionConfig;
            return this;
        }

        public MpGeneratorBuilder templateConfig( TemplateConfig templateConfig ){
            this.templateConfig = templateConfig;
            return this;
        }

        public MpGeneratorBuilder basePath( String basePath ){
            this.basePath = basePath;
            return this;
        }

        public MpGeneratorBuilder tablePrefix( String ...tablePrefix ){
            this.tablePrefix = tablePrefix;
            return this;
        }

        public MpGeneratorBuilder packageName( String packageName ){
            this.packageName = packageName;
            return this;
        }

        public MpGeneratorBuilder versionFieldName( String versionFieldName ){
            this.versionFieldName = versionFieldName;
            return this;
        }

        public MpGeneratorBuilder author( String author ){
            this.author = author;
            return this;
        }

        public MpGeneratorBuilder tables( String ...tables ){
            this.tables = tables;
            return this;
        }

        public MpGenerator build(){
            AutoGenerator mpg = new AutoGenerator();

            if( globalConfig == null ){
                globalConfig = new GlobalConfig();
                globalConfig.setFileOverride(true);
                globalConfig.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
                globalConfig.setEnableCache(false);// XML 二级缓存
                globalConfig.setBaseResultMap(true);// XML ResultMap
                globalConfig.setBaseColumnList(true);// XML columList
                globalConfig.setDateType(DateType.ONLY_DATE);
                globalConfig.setServiceName("%sService");
            }
            if( this.basePath != null ){
                globalConfig.setOutputDir( basePath );
            }else{
                globalConfig.setOutputDir( "C://#tmp" );
            }
            if( this.author == null ){
                throw new IllegalArgumentException("人员[author]不能为空");
            }else{
                globalConfig.setAuthor( author );
            }
            mpg.setGlobalConfig( globalConfig );

            if( this.dataSourceConfig == null ){
                throw new IllegalArgumentException("数据源[dataSourceConfig]不能为空");
            }
            mpg.setDataSource( dataSourceConfig );

            if( this.strategyConfig == null ){
                this.strategyConfig = new StrategyConfig();
                strategyConfig.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
                strategyConfig.setEntityColumnConstant(true);
            }
            if( tablePrefix != null ){
                strategyConfig.setTablePrefix( tablePrefix );
            }
            if( tables == null ){
                throw new IllegalArgumentException("表名[packageName]不能为空");
            }else{
                strategyConfig.setInclude( tables );
            }
            if( versionFieldName != null ){
                strategyConfig.setVersionFieldName( versionFieldName );
            }
            mpg.setStrategy( strategyConfig );

            if( this.packageConfig == null ){
                this.packageConfig = new PackageConfig();
                packageConfig.setController("controller");
                packageConfig.setEntity("model");
            }
            if( packageName == null ){
                throw new IllegalArgumentException("包名[packageName]不能为空");
            }else{
                packageConfig.setParent( packageName );
            }
            mpg.setPackageInfo( packageConfig );


            if( this.templateConfig == null ){
                templateConfig = new TemplateConfig();
                templateConfig.setController("/mybatis-templates/controller.java.vm");
                templateConfig.setService("/mybatis-templates/service.java.vm");
                templateConfig.setServiceImpl("/mybatis-templates/serviceImpl.java.vm");
                templateConfig.setEntity("/mybatis-templates/entity.java.vm");
                templateConfig.setMapper("/mybatis-templates/mapper.java.vm");
                templateConfig.setXml("/mybatis-templates/mapper.xml.vm");
            }
            mpg.setTemplate( templateConfig );

            return new MpGenerator( mpg );
        }
    }

    /**
     *ORACLE 生成演示
     * @param tablePerfix 表前缀
     * @param packageName 包名
     * @param versionFieldName 乐观锁栏位名称
     * @param tableNames 表名
     */
    public void generateByTables(String[] tablePerfix, String packageName, String versionFieldName, String author, String... tableNames) {
        AutoGenerator mpg = new AutoGenerator();
        // 选择 freemarker 引擎，默认 Veloctiy
        // mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        String basePath = "C://#tmp";
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(basePath);
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setDateType(DateType.ONLY_DATE);
        //gc.setKotlin(true);//是否生成 kotlin 代码
        gc.setAuthor("Ervin Chen");
        gc.setServiceName("%sService");
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        // gc.setMapperName("%sDao");
        // gc.setXmlName("%sDao");
        // gc.setServiceName("MP%sService");
        // gc.setServiceImplName("%sServiceDiy");
        // gc.setControllerName("%sAction");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.ORACLE);
        dsc.setTypeConvert(new OracleTypeConvert() {
            @Override
            public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                String t = fieldType.toLowerCase();
                if (t.contains("char")) {
                    return DbColumnType.STRING;
                } else {
                    if (!t.contains("date") && !t.contains("timestamp")) {
                        if (t.contains("number")) {
                            if (t.matches("number\\(+\\d\\)")) {
                                return DbColumnType.INTEGER;
                            }

                            if (t.matches("number\\(+\\d{2}+\\)")) {
                                return DbColumnType.LONG;
                            }

                            return DbColumnType.DOUBLE;
                        }

                        if (t.contains("float")) {
                            return DbColumnType.FLOAT;
                        }

                        if (t.contains("clob")) {
                            return DbColumnType.STRING;
                        }

                        if (t.contains("blob")) {
                            return DbColumnType.BLOB;
                        }

                        if (t.contains("binary")) {
                            return DbColumnType.BYTE_ARRAY;
                        }

                        if (t.contains("raw")) {
                            return DbColumnType.BYTE_ARRAY;
                        }
                    } else {
                        switch(globalConfig.getDateType()) {
                            case ONLY_DATE:
                                return DbColumnType.DATE;
                            case SQL_PACK:
                                return DbColumnType.TIMESTAMP;
                            case TIME_PACK:
                                return DbColumnType.LOCAL_DATE_TIME;
                        }
                    }

                    return DbColumnType.STRING;
                }
            }
        });
        dsc.setDriverName("oracle.jdbc.OracleDriver");
        dsc.setUsername("wip");
        dsc.setPassword("wip");
        dsc.setUrl("jdbc:oracle:thin:@192.168.138.109:1521/DEV");
        mpg.setDataSource(dsc);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
        strategy.setTablePrefix(tablePerfix);// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(tableNames); // 需要生成的表
        strategy.setVersionFieldName(versionFieldName);//乐观锁注解
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 自定义实体父类
        // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
        // 自定义实体，公共字段
        // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
        // 自定义 mapper 父类
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定义 service 父类
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定义 service 实现类父类
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定义 controller 父类
        // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
        // 【实体】是否生成字段常量（默认 false）
        // public static final String ID = "test_id";
        strategy.setEntityColumnConstant(true);
        // 【实体】是否为构建者模型（默认 false）
        // public User setName(String name) {this.name = name; return this;}
        //strategy.setEntityBuilderModel(true);
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(packageName);
        pc.setController("controller");
        pc.setEntity("model");
        mpg.setPackageInfo(pc);

        // 注入自定义配置，可以在 VM 中使用 cfg.abc 【可无】  ${cfg.abc}
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                map.put("restControllerStyle", true);
                this.setMap(map);
            }
        };

        /*// 自定义 xxListIndex.html 生成
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        focList.add(new FileOutConfig("/templatesMybatis/list.html.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return basePath + "html//" + tableInfo.getEntityName() + "ListIndex.html";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 自定义  xxAdd.html 生成
        focList.add(new FileOutConfig("/templatesMybatis/add.html.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return basePath + "html//" + tableInfo.getEntityName() + "Add.html";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        //  自定义 xxUpdate.html生成
        focList.add(new FileOutConfig("/templatesMybatis/update.html.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return basePath + "html//" + tableInfo.getEntityName() + "Update.html";
            }
        });
        cfg.setFileOutConfigList(focList);*/
        mpg.setCfg(cfg);

        // 关闭默认 xml 生成，调整生成 至 根目录
        /*TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        mpg.setTemplate(tc);*/

        // 自定义模板配置，可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改，
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置，也可以自定义模板名称
        TemplateConfig tc = new TemplateConfig();
        tc.setController("/mybatis-templates/controller.java.vm");
        tc.setService("/mybatis-templates/service.java.vm");
        tc.setServiceImpl("/mybatis-templates/serviceImpl.java.vm");
        tc.setEntity("/mybatis-templates/entity.java.vm");
        tc.setMapper("/mybatis-templates/mapper.java.vm");
        //tc.setXml("/templates/mapper.xml.vm");
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();

        // 打印注入设置【可无】
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }
}
